<?php

namespace App\Http\Controllers\Index;
use App\Model\Good;
use App\Model\Record;
use App\Model\Type;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;

class IndexController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $typeId = $request->get('type','');
        $keyword = $request->get('keyword','');
        $type= Type::orderBy('sort', 'desc')->pluck('name','id');
        $recomments = Good::where('cate','0')->limit(10)->get();
        $lists = Good::query();
        if (!empty($typeId)) {
            if ($typeId == 'today'){
                $lists->whereDate('created_at', date('Y-m-d'));
            }else{
                $lists->where('cate',$typeId);
            }
        }
        if (!empty($keyword)) {
            $lists->where('name','like','%'.$keyword.'%');
        }

        $lists = $lists->orderBy('created_at','desc')->paginate(9);

        $key = $request->ip().date('Y-m-d');
        $wecome = Redis::get($key);

        if (empty($wecome)) {
            Redis::set($key,'43');
            $num = Redis::get('visit_num');
            Redis::set('visit_num',Redis::get('visit_num') + 1);
            Redis::set(date('Y-m-d'),Redis::get(date('Y-m-d')) + 1);
        }
//        dd(Redis::get('visit_num'));
        return view('index.index',compact('type','lists','recomments'));
    }


    /**
     * Show the detail.
     *
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request, $id)
    {
        $model = Redis::get('model_'.$id);
        if (!$model) {
            $model = Good::find($id);
            Redis::set('model_'.$id,gzcompress(base64_encode(serialize($model))));
        }else{
            $model = unserialize(base64_decode(gzuncompress($model)));
        }

        $qun = Redis::get('qun');    //微信群二维码
        $touxiang = Redis::get('touxiang');//头像二维码

        //埋点
        $data = [
            'ip'=>$request->ip(),
            'date'=>date('Y-m-d'),
            'good_id'=>$id,
        ];
        $exit = Record::where($data)->first();
        if (empty($exit)) {
            Record::insert($data+['created_at'=>date('Y-m-d H:i:s'),]);
        }
        $type= Type::orderBy('sort', 'desc')->pluck('name','id');
        return view('index.show', compact('type', 'model','qun','touxiang'));
    }
}
